﻿using System;

using System.Net;
using System.Net.Sockets;

using System.Text;

namespace UdpSyncEchoServer
{
    class Program
    {   
        static void Main(string[] args)
        {
            Socket udpSock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            IPEndPoint localAddress = new IPEndPoint(IPAddress.Any,6001);
            udpSock.Bind(localAddress);
            Console.WriteLine("bind to {0}, waiting for clients",localAddress);

            byte[] recvData = new byte[1024];
            EndPoint remoteAddress = new IPEndPoint(IPAddress.Any,0);
            int recvLength;

            try
            {
                while (true)
                {
                    recvLength = udpSock.ReceiveFrom(recvData,ref remoteAddress);
                    string recvMsg = Encoding.ASCII.GetString(recvData,0,recvLength);
                    Console.WriteLine("received message[{0}] from [{1}]",recvMsg,remoteAddress.ToString());

                    // echo back
                    udpSock.SendTo(recvData,recvLength,SocketFlags.None,remoteAddress);
                }// while
            }
            finally
            {
                udpSock.Close();
                Console.WriteLine("socket is closed, program exits");
            }// finally
        }// Main
    }// class Program
}
